/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmBusquedaPersona.java
 *
 * Created on 14-jun-2011, 1:03:02
 */
package verins.GUI;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.table.DefaultTableModel;
import verins.BO.PersonaBO;
import verins.BO.PersonarnvBO;
import verins.BO.TipoPersonaBO;
import verins.Utils.Comunes;
import verins.beans.Persona;
import verins.beans.Personarnv;
import verins.beans.Tipopersona;

/**
 *
 * @author hectdx
 */
public class frmBusquedaPersona extends JDialog {

    public Object personaBusqueda=null;
    private List lstPersonas=null;
    private int tipopersona=3;
    /** Creates new form frmBusquedaPersona */
    public frmBusquedaPersona(JDialog ventP) {
        super(ventP,true);
        initComponents();
        verins.Utils.Comunes.centrarVentana(this);
        setValidadores();
        getRootPane().setDefaultButton(btnBuscar);
        lblCoincidencias.setVisible(false);
        btnSeleccionar.setVisible(false);
        txtDNI.requestFocus();
        llenarCombos();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtDNI = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtApPaterno = new javax.swing.JTextField();
        txtApMaterno = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtNombres = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblPersonas = new javax.swing.JTable();
        btnBuscar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        btnDetalle = new javax.swing.JButton();
        btnSeleccionar = new javax.swing.JButton();
        lblCoincidencias = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Búsqueda de personas");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Criterios de búsqueda"));

        jLabel1.setText("DNI");

        jLabel2.setText("Ap. paterno");

        jLabel3.setText("Ap. materno");

        jLabel4.setText("Nombres");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtNombres)
                            .addComponent(txtApMaterno, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtDNI, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtApPaterno, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(333, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtDNI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtApPaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtApMaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtNombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tblPersonas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "DNI", "Ap. Paterno", "Ap.Materno", "Nombres"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblPersonas);
        tblPersonas.getColumnModel().getColumn(0).setResizable(false);
        tblPersonas.getColumnModel().getColumn(1).setResizable(false);
        tblPersonas.getColumnModel().getColumn(2).setResizable(false);

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        btnDetalle.setText("Ver detalle");
        btnDetalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetalleActionPerformed(evt);
            }
        });

        btnSeleccionar.setText("Seleccionar");
        btnSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarActionPerformed(evt);
            }
        });

        lblCoincidencias.setText("Se han encontrado (0) coincidencias");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 678, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(lblCoincidencias)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 349, Short.MAX_VALUE)
                        .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnSeleccionar, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 193, Short.MAX_VALUE)
                        .addComponent(btnDetalle)
                        .addGap(231, 231, 231)
                        .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBuscar)
                    .addComponent(lblCoincidencias))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalir)
                    .addComponent(btnDetalle)
                    .addComponent(btnSeleccionar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        // TODO add your handling code here:
        Personarnv prnvTemp=null;
        Persona pTemp=null;
        lblCoincidencias.setVisible(false);
        if (validarCampos()){
            obtenerCriterios();
            if (tipopersona==3){//tipo rnv firmante
                prnvTemp=(Personarnv)personaBusqueda;
                if (!prnvTemp.getDni().equals("")){
                    personaBusqueda=PersonarnvBO.findByDNI(prnvTemp.getDni());
                    if (personaBusqueda==null) 
                        lblCoincidencias.setVisible(true);
                    else{
                        Comunes.limpiarTabla(tblPersonas);
                        //lstPersonas=null;
                        //btnDetalleActionPerformed(null);
                         lstPersonas=new ArrayList();
                        lstPersonas.add(personaBusqueda);
                        llenarTabla();
                    }
                }else{//demás criterios
                    lstPersonas=PersonarnvBO.findByCriterios(prnvTemp);
                    
                     if (lstPersonas!=null && lstPersonas.isEmpty()) 
                        lblCoincidencias.setVisible(true);
                    else lblCoincidencias.setVisible(false);
                }
            }else{
            //tipo persona
                pTemp=(Persona)personaBusqueda;
                 if (!pTemp.getDni().equals("")){
                personaBusqueda=PersonaBO.findByDNI(pTemp.getDni());
                    if (personaBusqueda==null) 
                        lblCoincidencias.setVisible(true);
                    else{
                        Comunes.limpiarTabla(tblPersonas);
                        lstPersonas=null;
                        btnDetalleActionPerformed(null);
                        lstPersonas=new ArrayList();
                        lstPersonas.add(personaBusqueda);
                    }
                }else{//demás criterios
                    lstPersonas=PersonaBO.findByCriterios(pTemp);
                    if (lstPersonas!=null && lstPersonas.isEmpty()) 
                        lblCoincidencias.setVisible(true);
                    else lblCoincidencias.setVisible(false);
                }
            }
            llenarTabla();
        }
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarActionPerformed
        // TODO add your handling code here
        obtenerPersonaSeleccionada();
        dispose();
    }//GEN-LAST:event_btnSeleccionarActionPerformed

    private void btnDetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetalleActionPerformed
        // TODO add your handling code here:
        frmPersona frm;
        obtenerPersonaSeleccionada();
        if (personaBusqueda!=null){
            if (tipopersona==3)
                frm=new frmPersona(this,((Personarnv)personaBusqueda).getDni());
            else
                frm=new frmPersona(this,((Persona)personaBusqueda).getDni());
            
            frm.setVisible(true);
        }
    }//GEN-LAST:event_btnDetalleActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        // TODO add your handling code here:
        
        dispose();
    }//GEN-LAST:event_btnSalirActionPerformed

    private Object obtenerPersonaSeleccionada(){
         if (lstPersonas!=null){
            int fila=tblPersonas.getSelectedRow();
                if (fila>=0){
                    personaBusqueda=lstPersonas.get(fila);
                } else 
                    personaBusqueda= null;
         }
           return personaBusqueda;
    }
    
    private void obtenerCriterios(){
        if (tipopersona==3){//rnv
            Personarnv prnvBusq=new Personarnv();
            prnvBusq.setDni(txtDNI.getText());
            prnvBusq.setApepaterno(txtApPaterno.getText());
            prnvBusq.setApematerno(txtApMaterno.getText());
            prnvBusq.setNombres(txtNombres.getText());
            
            personaBusqueda=prnvBusq;
        }else{//persona
            Persona prnvBusq=new Persona();
            prnvBusq.setDni(txtDNI.getText());
            prnvBusq.setApellidopaterno(txtApPaterno.getText());
            prnvBusq.setApellidomaterno(txtApMaterno.getText());
            prnvBusq.setNombres(txtNombres.getText());
            
            personaBusqueda=prnvBusq;
        }
    }
    
    private void setValidadores(){
        txtDNI.setDocument(new verins.Utils.LimitInput(8));
        //txtDNI.addKeyListener(verins.Utils.Verificador.verificaSoloNumeros());
        txtApPaterno.setDocument(new verins.Utils.LimitInput(30));
        txtApPaterno.addKeyListener(verins.Utils.Verificador.verificaSoloLetras());
        txtApMaterno.setDocument(new verins.Utils.LimitInput(30));
        txtApMaterno.addKeyListener(verins.Utils.Verificador.verificaSoloLetras());
        txtNombres.setDocument(new verins.Utils.LimitInput(20));
        //txtNombres.addKeyListener(verins.Utils.Verificador.verificaSoloLetras());
    }
    
    public void mostrarBotonAgregar(boolean op){
        btnSeleccionar.setVisible(op);
    }
    
    
    public void setearTipoPersona(Tipopersona tipo){
       
        tipopersona=tipo.getIdtipopersona();
        if (tipopersona!=3){//no debe mostrar detalle
        //tipo rnv
            btnDetalle.setVisible(false);
        }
    }
    
    private boolean validarCampos(){
        if (txtDNI.getText().length()==0
            && txtApMaterno.getText().length()==0    
            && txtApPaterno.getText().length()==0
            && txtNombres.getText().length()==0
                ){
            verins.Utils.Mensajes.alerta("Debe ingresar un criterio de búsqueda");
            return false;
        }
        return true;
    }
    
    private void llenarTabla(){
        DefaultTableModel dtm=(DefaultTableModel)tblPersonas.getModel();
        verins.Utils.Comunes.limpiarTabla(tblPersonas);
        if (lstPersonas!=null&& lstPersonas.size()>0){
            Iterator it=lstPersonas.iterator();
            while(it.hasNext()){
                if (tipopersona==3){
                Personarnv p=(Personarnv)it.next();
                Object fila[]=new Object[] {p.getDni(),
                                            p.getApepaterno(),
                                            p.getApematerno(),
                                            p.getNombres()};
                dtm.addRow(fila);
                }else{
                     Persona p=(Persona)it.next();
                    Object fila[]=new Object[] {p.getDni(),
                                                p.getApellidopaterno(),
                                                p.getApellidomaterno(),
                                                p.getNombres()};
                    dtm.addRow(fila);
                }
            }
            verins.Utils.Comunes.setearColumnas(tblPersonas);
        }
    }
    
    private void llenarCombos(){
       /* List lista=null;
        lista=TipoPersonaBO.findAll();
        verins.Utils.Comunes.llenarCombo(cmbTipo,lista);
        */
    }
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new frmBusquedaPersona(null).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnDetalle;
    private javax.swing.JButton btnSalir;
    private javax.swing.JButton btnSeleccionar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCoincidencias;
    private javax.swing.JTable tblPersonas;
    private javax.swing.JTextField txtApMaterno;
    private javax.swing.JTextField txtApPaterno;
    private javax.swing.JTextField txtDNI;
    private javax.swing.JTextField txtNombres;
    // End of variables declaration//GEN-END:variables
}
